import * as THREE from '@yushu/three-base';
import _, { pick } from 'lodash';
import { RevitLoader } from '@yushu/core3d';
import Stats from 'stats.js';
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min';
import { getSceneUrl, RevitMaterialLoader,
    applyMapForMesh, 
    OBJLoader, SceneLoader, EffectLoader } from '@yushu/effecttool';
import { ShaderPass } from '@yushu/three-base/three-extends/jsm/postprocessing/ShaderPass';
import { DenoiserRenderPass } from '../renderPass/DenoiserRenderPass';
import { DenoiseMaterial } from '../materials/DenoiseMaterial';
import { CloudsShader } from '../shaders/cloudsShader';
import { SSRPass } from '@yushu/three-base/three-extends/jsm/postprocessing/SSRPass.js';
import { CloudsPass } from '../renderPass/CloudsPass';
import { GammaCorrectionShader } from '@yushu/three-base/three-extends/jsm/shaders/GammaCorrectionShader';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader';
import { MTLLoader } from '../utils/MTLLoader';
import PELoader from '../loader/peloader';
import U3dMaterlsLoader from '../loader/loaders/u3dMaterlsLoader';
import CameraManager from '../managers/camera';
import { OrbitControls } from '../utils/OrbitControls';
import { mergeBufferGeometries } from '@yushu/three-base/three-extends/jsm/utils/BufferGeometryUtils';
import GeneralScene from './coreScenes/GeneralScene';
import { getAllUrlParams, angle2rad, forMaterial } from '../utils/utils';
import ParticleSystem from '../shaders/particle/libs/system';
import TunnelEmitter from '../shaders/particle/libs/emitters/tunnel';

const { setMeshUpToY } = THREE.baseUtils;

import axios from 'axios';

SceneLoader.setFileHost('https://cdn.meos.center')
const myObject = {
    变幻调试开关: true,
    帧率工具开关: true,
    坐标轴线开关: true,
    预览工具开关: true,
    生长动画开关: true,
    炸开动画开关: false,
    所在环境: 'dev',
    相机机位: '正面',
};
const growthAnime = {
    animationMode: '生长方式',
    delay: '延迟时长',
    duration: '持续时长',
    isCircle: '循环'
}
const boomAnime = {
    boomType: '炸开方式',
    delay: '延迟时长',
    duration: '持续时长',
    isLoop: '循环'
}
const idToObject = [];
const ssrParams = {
    enableSSR: true,
    autoRotate: true,
    otherMeshes: true,
    groundReflector: true,
};
let ssrPass;
const selects = [];
export default class PreviewScene extends GeneralScene {
    constructor() {
        super();
        this.meshsMap = {};
        this.skinedMesh = {};
        this.planetPosition = {};
        this.planetRotation = {};
        this.planetMesh = [];
        this.progress = 0;
        this.rad = 0;
        this.env = 'dev';
        /** 事件相关全局变量 */
        this.eventMap = {}; // 存储事件
        this.eventMap.ready = {};
        this.needTransform = true;
        const params = getAllUrlParams();
        const {
            meshurl, floor, projectid, scenename
        } = params;
    }

    async initParticle() {
        const loader = new FBXLoader();
        this.Scene.background = new THREE.Color(0, 0, 0);
        this.actions = [];
        loader.load(
            'https://cdn.meos.center/k2g/particle/img/%E6%B0%B4%E6%99%AF%E7%B3%BB%E7%BB%9F%E6%B5%8B%E8%AF%95%E6%A8%A1%E5%9E%8B.fbx',
            (obj) => {
                console.log(obj);
                this.Scene.add(obj);
            }
        );

        const t = await new THREE.TextureLoader().loadAsync('https://cdn.meos.center/k2g/particle/img/spikey.png');
        console.log(t)
        this.ps = new ParticleSystem({
            emitter: new TunnelEmitter(t, 100, 1.)
        })

        this.ps.mesh.position.set(85, -25, -15)
        this.Scene.add(this.ps.mesh);
        this.ps.start();

        this.ps1 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 70, 0.7)
        })

        this.ps1.mesh.position.set(95, -25, -15)
        this.Scene.add(this.ps1.mesh);
        this.ps1.start();
        

        this.ps2 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 70, 0.7)
        })

        this.ps2.mesh.position.set(75, -25, -15)
        this.Scene.add(this.ps2.mesh);
        this.ps2.start();

        this.ps3 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 70, 0.7)
        })

        this.ps3.mesh.position.set(85, -25, -5)
        this.Scene.add(this.ps3.mesh);
        this.ps3.start();

        this.ps4 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 70, 0.7)
        })

        this.ps4.mesh.position.set(85, -25, -25)
        this.Scene.add(this.ps4.mesh);
        this.ps4.start();

        this.ps5 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 50, 0.3)
        })

        this.ps5.mesh.position.set(93, -25, -7)
        this.Scene.add(this.ps5.mesh);
        this.ps5.start();
        
        this.ps6 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 50, 0.3)
        })
        this.ps6.mesh.position.set(93, -25, -23)
        this.Scene.add(this.ps6.mesh);
        this.ps6.start();

        this.ps7 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 50, 0.3)
        })

        this.ps7.mesh.position.set(78, -25, -7)
        this.Scene.add(this.ps7.mesh);
        this.ps7.start();
        
        this.ps8 = new ParticleSystem({
            emitter: new TunnelEmitter(t, 50, 0.3)
        })
        this.ps8.mesh.position.set(78, -25, -23)
        this.Scene.add(this.ps8.mesh);
        this.ps8.start();
    }
    Create() {
        if (this.load) return;
        this.controls = new OrbitControls(this.camera, this.labelRenderer.domElement);
        // 相机控制
        this.cameraManager = new CameraManager();
        this.cameraManager.camera = this.camera;
        this.cameraManager.controls = this.controls;
        const params = getAllUrlParams();
        this.clock = new THREE.Clock();
        if(!this.stats){
            this.stats = new Stats();
            this.dom.appendChild(this.stats.domElement);
        }
        const {
            env, meshurl, pick, floor, projectid, 
            scenename, test, test2, test3, building, preview
        } = params;
        if (scenename) {
            const pathNameArr = scenename.split('-');
            this.projectId = pathNameArr[0];
            this.sceneName = pathNameArr[1];
            // this.axeshelper = new THREE.AxesHelper(15500)
            // this.axeshelper.visible = true;
            this.reallyGroup = new THREE.Group();
            // this.Scene.add(this.axeshelper);
            this.Scene.add(this.reallyGroup);
            if(env){
                this.env = env;
                myObject['所在环境'] = env;
            }
            this.realHullFloorMap = {};
            // 写实场景加载器
            this.realisticSceneLoader = new SceneLoader(
                this.env, this.projectId, 
                this.sceneName, this.renderer, {
                preview
            });
            this.time = {
                value: 0
            };
            this.StartTime = {
                value: 0
            };
            this.isStart = false; // 是否启动

            if (this.sceneName) {
                this.loadScene().then(() => {
                   
                });
            }
            this.controls.enablePan = true;
            // this.controls.autoRotate = true;
            // this.controls.autoRotateSpeed = 0.5;
            this.controls.maxPolarAngle = Math.PI / 2;

            this.raycaster = new THREE.Raycaster();
            this.pointer = new THREE.Vector2([0, 0]);
            window.addEventListener('keydown', (e) => {
                if(e.key === 'Escape'){
                    this.stats.dom.style.display = 'none';
                }
            }, false);
            this.bindEvent();
        } else if (building) {
            this.particleManagers = [];
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.raycaster = new THREE.Raycaster();
            this.pointer = new THREE.Vector2([0, 0]);
            // this.Scene.add(new THREE.AxesHelper(15500));

            this.Scene.background = new THREE.Color('#E8EEF1'); // 背景色
            this.bindEvent();
            // this.createLightAndShadow(); // 处理光影  单独拿出来

            this.initCamera(); // 初始化相机
            this.initBuildingBim().then(() => {
                this.restoreCamera();
            });
        } else if (test) {
            this.particleManagers = [];
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.Scene.add(new THREE.AxesHelper(15500));

            this.Scene.background = new THREE.Color('#5c5f66'); // 背景色

            this.createLightAndShadow(); // 处理光影  单独拿出来

            this.initCamera(); // 初始化相机
        
            this.testModel();
        } else if (test2) {
            this.particleManagers = [];
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.Scene.add(new THREE.AxesHelper(15500));

            this.Scene.background = new THREE.Color('#5c5f66'); // 背景色

            this.createLightAndShadow(); // 处理光影  单独拿出来

            this.initCamera(); // 初始化相机
            this.testModel2();
        } else if (test3) {
            this.particleManagers = [];
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.Scene.add(new THREE.AxesHelper(15500));

            this.Scene.background = new THREE.Color('#5c5f66'); // 背景色

            this.createLightAndShadow(); // 处理光影  单独拿出来

            this.initCamera(); // 初始化相机
            this.testModel3();
        } else if (pick) {
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.Scene.background = new THREE.Color('#5c5f66'); // 背景色
            this.raycaster = new THREE.Raycaster();
            this.pointer = new THREE.Vector2();
            this.createLightAndShadow(); // 处理光影  单独拿出来
            this.bindEvent2();
            this.initCamera(); // 初始化相机
            
            this.controls.target.set(0, 0, 0);
            const boxWidth = 1;
            const boxHeight = 1;
            const boxDepth = 1;
            const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
            
            function rand(min, max) {
                if (max === undefined) {
                    max = min;
                    min = 0;
                }
                return min + (max - min) * Math.random();
            }
            
            function randomColor() {
                return `hsl(${rand(360) | 0}, ${rand(50, 100) | 0}%, 50%)`;
            }
            
            const numObjects = 100;
            for (let i = 0; i < numObjects; ++i) {
                const id = i;
                const material = new THREE.MeshPhongMaterial({
                    color: randomColor(),
                    emissive: '#000000'
                });
                
                const cube = new THREE.Mesh(geometry, material);
                this.Scene.add(cube);
                idToObject[id] = cube;
                
                cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
                cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
                cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
                pickingMaterial.color = new THREE.Color(i);
                const pickingCube = new THREE.Mesh(geometry, pickingMaterial.clone());
                pickingScene.add(pickingCube);
                pickingCube.position.copy(cube.position);
                pickingCube.rotation.copy(cube.rotation);
                pickingCube.scale.copy(cube.scale);
            }

        } else {
            this.particleManagers = [];
            this.root = new THREE.Object3D();
            this.Scene.add(this.root);
            this.Scene.add(new THREE.AxesHelper(15500));

            this.Scene.background = new THREE.Color('#5c5f66'); // 背景色

            this.createLightAndShadow(); // 处理光影  单独拿出来

            this.initCamera(); // 初始化相机
            this.initModelBim().then(() => {
                this.restoreCamera();
            });
        }
    }

    initClouds() {
        this.clouds = {
            renderTarget: new THREE.WebGLRenderTarget(this.canvasWidth, this.canvasHeight),
            cloudsMaterial: new THREE.ShaderMaterial({
                uniforms: CloudsShader.uniforms,
                vertexShader: CloudsShader.vertexShader,
                fragmentShader: CloudsShader.fragmentShader,
                depthTest: false,
                blending: THREE.NoBlending
            })
        }
    }

    async loadScene() {
        const loadPromise = [];
        await this.realisticSceneLoader.init();
        loadPromise.push(this._loadSceneLights());
        loadPromise.push(this._loadSceneMeshs());
        loadPromise.push(this._loadSceneCamera());
        await Promise.allSettled(loadPromise);
        setTimeout(async () => {
            this.skyBox = await this.realisticSceneLoader.getSkybox();
		    this.skyBox && this.Scene.add(this.skyBox);
            await this._loadSceneBackground();
        }, 1000);
    }

    async _loadSceneLights() {
        const g = await this.realisticSceneLoader.initLightAndShadow();
        this.Scene.add(g);
    }

    _loadSceneBackground() {
        this.realisticSceneLoader.getSceneBackground(this.renderer).then((rst) => {
            this.Scene.background = rst;
            this.load = true;
        });
    }

    _loadSceneCamera() {
        return this.realisticSceneLoader.getCameraModel().then((cameraModel) => {
            this.setCamera(cameraModel);
            this.controls.minDistance = this.controls.target.distanceTo(this.camera.position) / 2;
            this.controls.maxDistance = this.controls.target.distanceTo(this.camera.position) * 2;
        });
    }

    setCamera(model) {
        const {
            fov, left, right, bottom, top, far, near, position, target
        } = model;
        this.camera.fov = fov;
        this.camera.left = left;
        this.camera.right = right;
        this.camera.bottom = bottom;
        this.camera.top = top;
        this.camera.up.set(0, 1, 0);
        this.camera.position.set(position.x, position.y, position.z);
        // this.camera.target.set(target.x, target.y, target.z);
        this.camera.far = far;
        this.camera.near = near;
        this.controls.target.set(target.x, target.y, target.z);
        this.camera.updateProjectionMatrix();
        this.controls.update();
    }

    _loadSceneMeshs() {
        console.log('loadscene mesh')
        // eslint-disable-next-line no-return-await
        return new Promise((resolve) => {
            this.realisticSceneLoader.loadMeshes(false, async (object, progress) => {
                console.log(object)
                this.reallyGroup.add(object);
                
                this.loadProgress = progress * 98;
                if (this.realisticSceneLoader.loadError) {
                    this.loadError = true;
                }
                return object;
            }).then(() => {
                if (this.realisticSceneLoader.loadError) {
                    this.loadError = true;
                }
                resolve();
            });
        });
    }


    getBones(b, r) {
        if (b.animations && b.animations.length) {
            console.log(b.animations);
        }
        if (b.type === 'Bone') {
            r.push(b);
            if (b.children.length) {
                for (let i = 0; i < b.children.length; i++) {
                    this.getBones(b.children[i], r);
                }
            }
        }
        return r;
    }

    getEnv() {
        // return 'EffectToolStable'; // 生产
        if (this.env === 'production') {
            return '生产环境'; // 生产
        } if (this.env === 'test') {
            return '测试环境'; // 测试
        }
        return '开发环境'; // 开发
    }
    initCamera() {
        this.camera.fov = 45;
        this.camera.position.set(200, 200, -400);
        this.camera.up.set(0, 1, 0);
        this.camera.far = 20000;
        this.controls.minDistance = 0;
        this.controls.maxDistance = 100000;
        this.controls.maxAzimuthAngle = Infinity;
        this.controls.minAzimuthAngle = -Infinity;
        this.controls.dampingFactor = 0.7;
        this.controls.panSpeed = 2;
        this.controls.mouseButtons = {
            LEFT: THREE.MOUSE.ROTATE,
            MIDDLE: THREE.MOUSE.DOLLY,
            RIGHT: THREE.MOUSE.PAN
        };
        this.controls.target.set(200, 0, 0);
    }

    /**
     * 初始化光影
     */
    async initLightAndShadow2() {
        try {
            const openHelper = false;
            const openCamerHelper = false;

            const lights = [];

            const lightModels = [
                {
                    type: 1,
                    color: 'FFFFFF',
                    intensity: 0.7,
                    range: 10,
                    spotAngle: 30,
                    shadow: {
                        type: 2,
                        strength: 1,
                        bias: 0.05,
                        normalBias: 0.4,
                        nearPlane: 0.2
                    },
                    bounceIntensity: 1,
                    target: {
                        x: -100,
                        y: 0,
                        z: 0
                    },
                    shadowCamera: {
                        near: 10,
                        far: 2703,
                        left: -1200,
                        right: 1200,
                        top: 1200,
                        bottom: -626.4,
                        textureWidth: 2048,
                        textureHeight: 2048
                    },
                    flareThreeJSDatas: null,
                    position: {
                        x: 293,
                        y: 1021,
                        z: -1139
                    },
                    eulerAngles: {
                        x: 40.2771873,
                        y: 340.963531,
                        z: 0
                    },
                    rotation: {
                        x: 0.339552283,
                        y: -0.1552516,
                        z: 0.0569326244,
                        w: 0.9259373
                    },
                    scale: {
                        x: 0,
                        y: 0,
                        z: 0
                    }
                }
            ];
            lightModels.forEach(light => {
                let lightInstance = null;
                // eslint-disable-next-line default-case
                switch (light.type) {
                case 1: {
                    lightInstance = new THREE.DirectionalLight(`#${light.color}`, light.intensity); // 平行光
                    lightInstance.target = new THREE.Object3D();
                    lightInstance.target.position.set(-light.target.x, light.target.y, light.target.z);
                    this.Scene.add(lightInstance.target);
                    if (openHelper) {
                        const helper = new THREE.DirectionalLightHelper(lightInstance);
                        this.Scene.add(helper);
                    }
                    break;
                }
                case 2: {
                    lightInstance = new THREE.PointLight(`#${light.color}`, light.intensity); // 点光源
                    if (openHelper) {
                        this.Scene.add(new THREE.PointLightHelper(lightInstance));
                    }
                    break;
                }
                case 3: {
                    lightInstance = new THREE.SpotLight(`#${light.color}`, light.intensity); // 聚光灯
                    if (light.spotAngle !== undefined) {
                        lightInstance.angle = light.spotAngle;
                    }
                    if (openHelper) {
                        this.Scene.add(new THREE.SpotLightHelper(lightInstance));
                    }
                    break;
                }
                case 4: {
                    lightInstance = new THREE.RectAreaLight(`#${light.color}`, light.intensity); // 矩形光
                    break;
                }
                }
                if (!lightInstance) return;
                lightInstance.position.set(-light.position.x, light.position.y, light.position.z);
                if (light.range !== undefined) {
                    lightInstance.distance = light.range;
                }
                if (light.eulerAngles !== undefined) {
                    lightInstance.setRotationFromEuler(new THREE.Euler(angle2rad(-light.eulerAngles.x), angle2rad(light.eulerAngles.y), angle2rad(light.eulerAngles.z), 'XYZ'));
                }
                lightInstance.color.convertSRGBToLinear();
                this.Scene.add(lightInstance);

                // TODO light.bounceIntensity 反射强度没有解析

                // 处理阴影
                if (light.shadow) {
                    lightInstance.castShadow = light.shadow.type !== 0; // 是否开启光照
                    // if (light.shadow.bias !== undefined) {
                    lightInstance.shadow.bias = -0.001;
                    // }
                    if (light.shadow.normalBias !== undefined) {
                        lightInstance.shadow.normalBias = light.shadow.normalBias;
                    }
                    if (light.shadow.strength !== undefined) { // strength先解析为 radius 试试
                        lightInstance.shadow.radius = light.shadow.strength;
                    }
                    // 给阴影加相机
                    if (light.shadowCamera) {
                        lightInstance.shadow.mapSize.width = light.shadowCamera.textureWidth;
                        // lightInstance.shadow.mapSize.width = 8192;
                        lightInstance.shadow.mapSize.height = light.shadowCamera.textureHeight;
                        // lightInstance.shadow.mapSize.height = 8192;
                        lightInstance.shadow.camera.near = light.shadowCamera.near;
                        lightInstance.shadow.camera.far = light.shadowCamera.far;
                        lightInstance.shadow.camera.left = light.shadowCamera.left;
                        lightInstance.shadow.camera.right = light.shadowCamera.right;
                        lightInstance.shadow.camera.top = light.shadowCamera.top;
                        lightInstance.shadow.camera.bottom = light.shadowCamera.bottom;
                        if (openCamerHelper) {
                            this.Scene.add(new THREE.CameraHelper(lightInstance.shadow.camera));
                        }
                    }
                }
                lights.push(lightInstance);
            });

            const renderSettingModel = {
                "resoution": {
                  "x": 1423,
                  "y": 1303
                },
                "clearFlag": 2,
                "backGroundColor": "EBF7FF",
                "fog": false,
                "fogColor": "808080FF",
                "fogMode": 3,
                "fogDensity": 0.01,
                "linearFogStart": 0,
                "linearFogEnd": 300,
                "ambientSkyColor": "C0C0C0FF",
                "ambientEquatorColor": "1D2022FF",
                "ambientGroundColor": "0C0B09FF",
                "ambientIntensity": 0.46,
                "ambientMode": 3,
                "skyboxMaterial": {
                  "guid": null,
                  "Tint": null,
                  "Exposure": 0,
                  "Rotation": 0
                },
                "reflection": {
                  "reflectionMapId": "",
                  "intensity": 1
                }
            }

           if (renderSettingModel.ambientMode === 3) {
                // 环境光
                const light = new THREE.AmbientLight(`#${renderSettingModel.ambientSkyColor.slice(0, 6)}`);
                // const light = new THREE.AmbientLight('#ffffff', renderSettingModel.ambientIntensity);
                light.color.convertSRGBToLinear();
                this.Scene.add(light);
            }
            if (renderSettingModel.clearFlag === 2) { // 使用背景色不使用天空盒子
                this.Scene.background = new THREE.Color(`#${renderSettingModel.backGroundColor}`);
                // this.Scene.background.convertSRGBToLinear();
            }  else {
                this.Scene.background = null;
            }

            return { lights };
        } catch (e) {
            console.error(e);
            return e;
        }
    }

    createLightAndShadow() {
        /** ************************  灯光调试  *********************************** */
        // 平行光 配置
        const height = 150;
        const qulityH = 512;
        const qulityM = 1024;
        const qulityL = 512;
        const castShadowSet = [false, false, false, false, false];
        const power = 0.4;
        // 点光 配置
        const pointHeight = 200;
        const pointPower = 0.1;
        // 环境光
        this.amlight = new THREE.AmbientLight('#b5b5b5', 1);

        this.amlight.up.set(0, 1, 0);
        this.Scene.add(this.amlight);
        this.light1 = new THREE.DirectionalLight(0xffffff, 1);
        this.light1.position.set(300, 350, -100);
        this.light1.castShadow = castShadowSet[0];
        this.light1.shadow.camera.right = 20;
        this.light1.shadow.camera.left = -20;
        this.light1.shadow.camera.top = 20;
        this.light1.shadow.camera.bottom = -20;

        this.light1.shadow.mapSize.width = qulityL;
        this.light1.shadow.mapSize.height = qulityL;
        this.light1.shadow.radius = 1;
        this.light1.target.position.set(0, 0, 0);
        this.Scene.add(this.light1);
    }

     /**
     * 初始化相机
     */
    async changeCameraModel(cameraModel) {
        try {

            if(cameraModel.orthographic){
                // this.camera = new THREE.OrthographicCamera(this.canvasWidth / -2, this.canvasWidth / 2, this.canvasHeight / 2, this.canvasHeight / -2, 0, 1000);
                this.camera = new THREE.OrthographicCamera(cameraModel.orthoGraphicModel.left, cameraModel.orthoGraphicModel.right, cameraModel.orthoGraphicModel.top, cameraModel.orthoGraphicModel.bottom, 0, cameraModel.orthographicSize * 4);
                this.camera.position.set(-cameraModel.position.x, cameraModel.position.y, cameraModel.position.z);
                this.camera.updateProjectionMatrix();
                this.camera.lookAt(new THREE.Vector3(-cameraModel.targetPos.x, cameraModel.targetPos.y, cameraModel.targetPos.z));
                this.controls.object = this.camera;
                this.controls.target.set(-cameraModel.targetPos.x, cameraModel.targetPos.y, cameraModel.targetPos.z);
            }else{
                this.camera.position.set(-cameraModel.position.x, cameraModel.position.y, cameraModel.position.z);
                this.camera.near = cameraModel.nearClipPlane;
                this.camera.far = cameraModel.farClipPlane;
                this.camera.fov = cameraModel.fieldOfView;
                this.camera.updateProjectionMatrix();
                this.controls.target.set(-cameraModel.targetPos.x, cameraModel.targetPos.y, cameraModel.targetPos.z);
                this.controls.minDistance = this.controls.target.distanceTo(this.camera.position) / 2;
                this.controls.maxDistance = this.controls.target.distanceTo(this.camera.position) * 2;
            }

            return true;
        } catch (e) {
            console.error(e);
            return e;
        }
    }
    
    pick() {
        console.log(this.pointer);
        this.camera.setViewOffset( this.renderer.domElement.width, this.renderer.domElement.height, this.pointer.x * window.devicePixelRatio | 0, this.pointer.y * window.devicePixelRatio | 0, 1, 1 );

        // render the scene

        this.renderer.setRenderTarget( pickingTexture );
        this.renderer.render( pickingScene, this.camera );

        // clear the view offset so rendering returns to normal

        this.camera.clearViewOffset();

        //create buffer for reading single pixel

        const pixelBuffer = new Uint8Array( 4 );

        //read the pixel

        this.renderer.readRenderTargetPixels( pickingTexture, 0, 0, 1, 1, pixelBuffer );

        //interpret the pixel as an ID

        const id = ( pixelBuffer[ 0 ] << 16 ) | ( pixelBuffer[ 1 ] << 8 ) | ( pixelBuffer[ 2 ] );
        console.log(idToObject);
        const data = idToObject[ id ];
       

        if ( data ) {
            console.log(data);
            data.material.color = new THREE.Color('#ff0000');
        }
    }

    createPanel() {
        const sceneOptions = this.realisticSceneLoader.sceneOption;
        this.panel = new GUI({ width: 310 });
        const folder4 = this.panel.addFolder('光颜色');
        const requestData = {
            projectId: this.projectId,
            sceneName: this.sceneName,
            env: 'dev',
            materials: {},
            lights: {}
        };
        const data = {
            '保存设置'() {
                axios({
                    url: 'https://www.yushu.biz/revitapi/saveMaterial',
                    method: 'post',
                    responseType: 'json',
                    data: requestData
                }).then(res => {
                    console.log(res);
                })
            }
        }
        // let j = 0;
        // for(let i of this.realisticSceneLoader.efficientMaterialMap.keys()) {
        //     j++;
        //     const mat = this.realisticSceneLoader.efficientMaterialMap.get(i);
        //     requestData['materials'][i] = {
        //     }
        //     data['color' + j] = mat.color.getHexString();
        //     data['opacity' + j] = mat.opacity;
        //     folder4.addColor(data, 'color' + j).onChange((value) => {
        //         requestData['materials'][i].color = value.replace( '#', '' );
        //         this.handleColorChange(mat.color, value, true)
        //     });
        //     folder4.add(data, 'opacity' + j, 0, 1).onChange((value) => {
        //         mat.opacity = value;
        //         requestData['materials'][i].opacity = value;
        //     });
        // }
        
        let l = 0;
        this.Scene.traverse((c) => {
            if(c.isDirectionalLight){
                requestData.lights['direction'] = {}
                l++;
                data['light' + l] = c.color.getHexString();
                data['intensity' + l] = c.intensity;
                folder4.addColor(data, 'light' + l).onChange((value) => {
                    requestData.lights['direction'].color = value.replace('#', '');
                    if ( typeof value === 'string' ) {
                        value = value.replace( '#', '0x' );
                    }
                    
                    c.color.setHex(value);
                    c.color.convertSRGBToLinear();
                });
                folder4.add(data, 'intensity' + l, 0, 1).onChange((value) => {
                    c.intensity = value;
                    requestData.lights['direction'].intensity = value;
                });
                
            }else if(c.isAmbientLight) {
                requestData.lights['ambient'] = {}
                l++;
                data['light' + l] = c.color.getHexString();
                data['intensity' + l] = c.intensity;
                folder4.addColor(data, 'light' + l).onChange((value) => {
                    requestData.lights['ambient'].color = value.replace('#', '');
                    if ( typeof value === 'string' ) {
                       value = value.replace( '#', '0x' );
                    }
                    c.color.setHex(value);
                    c.color.convertSRGBToLinear();
                });
                folder4.add(data, 'intensity' + l, 0, 1).onChange((value) => {
                    c.intensity = value;
                    requestData.lights['ambient'].intensity = value;
                });

            }
        })
        folder4.add(data, '保存设置');
        
        this.previewCheck = this.panel.add(myObject, '预览工具开关').onChange(value => {
            if(value){
                this.panel.domElement.style.display = 'flex'
            }else{
                this.panel.domElement.style.display = 'none'
                iqwerty.toast.toast('按ESC按键退出', {
                    settings: {
                        duration: 2000,
                    },
                    style: {
                        main: {
                            background: '#1f1f1f',
                            fontSize: '14px',
                            width: '200px',
                            padding: '5px',
                            top: '60px',
                            bottom: 'auto',
                            transform: 'translateY(100%) translateZ(0px)'
                        }
                    }
                });
            }
        });
        const folder0 = this.panel.addFolder('基本设置');
        const settings = {
            强制刷新: () => { this.refreshScene(); },
        };
        this.panel.title('EFT效果预览工具');
        folder0.add(myObject, '变幻调试开关').onChange(value => {
            this.refreshScene();
        });
        folder0.add(myObject, '坐标轴线开关').onChange(value => {
            if(value){
                this.axeshelper.visible = true
            }else{
                this.axeshelper.visible = false
            }
        })
        folder0.add(myObject, '帧率工具开关').onChange( value => {
            if(value){
                this.stats.dom.style.display = 'block';
            }else{
                this.stats.dom.style.display = 'none';
            }
        });
        
        folder0.add(myObject, '生长动画开关').onChange(value => {
            this.clock.start();
            this.cancelGrowAnimation();
            this.reset();
        });
        folder0.add(myObject, '炸开动画开关').onChange(value => {
            this.boomAnimation();
            this.cancelBoomAnimation();
            this.reset();
        });
        folder0.add(myObject, '所在环境', { 开发环境: 'dev', 测试环境: 'test', 生产环境: 'production' }).onChange(value => {
            console.log(value);
            requestData.env = value;
            this.refreshScene();
        }) 

        const { cameraSeatModels } = sceneOptions;

        const obj = {}

        cameraSeatModels && cameraSeatModels.map(c => {
            obj[c.seatName] = c.cameraModel;
        })

        folder0.add(myObject, '相机机位', obj).onChange(value => {
            console.log(value);
            this.changeCameraModel(value);
        }) 

        folder0.add(settings, '强制刷新');
        const folder1 = this.panel.addFolder('场景信息预览');
        const folder1dom = folder1.domElement.getElementsByClassName('children')[0];
        folder1dom.innerHTML = '<div class="controller"><div class="name">项目名称</div><label class="widget">' + this.projectId + '</label></div>' +
        '<div class="controller"><div class="name">场景名称</div><label class="widget">' + this.sceneName + '</label></div>' + 
        '<div class="controller"><div class="name">所在环境</div><label class="widget">' + this.getEnv() + '</label></div>' +
        '<div class="controller"><div class="name  anime-title">加载时长</div><label class="widget">' + this.loadTime / 1000 + '秒</label></div>' +
        '<div class="controller"><div class="name">资源大小</div><label class="widget">' + (this.totalLoadSize / 1000 / 1000).toFixed(2) + 'Mb</label></div>' 
        const folder2 = this.panel.addFolder('生长动画信息预览');

        const clipModels = sceneOptions.clipModels;
        let growthHtml = ''
        if(clipModels){
            for(let i = 0; i< clipModels.length; i++){
                const clipModel = clipModels[i];
                growthHtml += '<div class="controller anime-title"><div class="name"><strong>动画' + (i+1) + '</strong></div></div>'
                Object.keys(growthAnime).forEach(k => {
                    growthHtml += '<div class="controller"><div class="name">' + growthAnime[k] + '</div><label class="widget">' + clipModel[k] + '</label></div>'
                })
            }
        }
        
        folder2.domElement.getElementsByClassName('children')[0].innerHTML += growthHtml
        folder2.close();
        const folder3 = this.panel.addFolder('炸开动画信息预览');
        const boomModels = sceneOptions.autoBooms;
        let boomHtml = ''
        if(boomModels){
            for(let i = 0; i< boomModels.length; i++){
                const boomModel = boomModels[i];
                boomHtml += '<div class="controller anime-title"><div class="name"><strong>动画' + (i+1) + '</strong></div></div>'
                Object.keys(boomAnime).forEach(k => {
                    boomHtml += '<div class="controller"><div class="name">' + boomAnime[k] + '</div><label class="widget">' + boomModel[k] + '</label></div>'
                })
            }
        }
        
        folder3.domElement.getElementsByClassName('children')[0].innerHTML += boomHtml
        folder3.close();
        // data['color' + key] = element.material.color.getHexString();
    }

    testModel() {
        const params = getAllUrlParams();

        const {
            meshname
        } = params;
        const loader = new OBJLoader();
        const mloader = new MTLLoader();
        mloader.load(
            `https://cdn.meos.center/EffectToolTest/Pj9909990006/PubLib/ProjectComponent/ACCCCC/ACCCCC-%E7%A6%BB%E5%BF%83%E5%86%B7%E6%B0%B4%E6%9C%BA%E7%BB%84/ACCCCC-%E7%A6%BB%E5%BF%83%E5%86%B7%E6%B0%B4%E6%9C%BA%E7%BB%84.mtl`,
            (materials) => {
                loader.setMaterials(materials).load(
                    `https://cdn.meos.center/EffectToolTest/Pj9909990006/PubLib/ProjectComponent/ACCCCC/ACCCCC-%E7%A6%BB%E5%BF%83%E5%86%B7%E6%B0%B4%E6%9C%BA%E7%BB%84/ACCCCC-%E7%A6%BB%E5%BF%83%E5%86%B7%E6%B0%B4%E6%9C%BA%E7%BB%84.obj`,
                    (object) => {
                        this.Scene.add(object);
   
                        const box3 = new THREE.Box3();
                        box3.setFromObject(object);
                        this.cameraManager.setCamera(box3, new THREE.Vector3(1, 1, 1).normalize(), false, 1.2, false);
                        this.load = true;
                        this.stopLoading();
                    }
                );
            }
        );
    }

    handleEvent(event) {
        this.raycaster.setFromCamera(this.pointer, this.camera);
        const intersects = this.raycaster.intersectObjects(this.Scene.children);
        this.clickedObj = intersects.find(intersect => {
            const { object } = intersect;
            // console.log(object)
            return object && object.id && object.revitType !== 'wall';
        });
       //  const meshUrl = this.idToInstanceIdMap.get(this.clickedObj.object.id);
       // const id = this.instanceIdToIdMap.get('119720/-96862');
       // this.triggerBoomAnimation(meshUrl);
    }

    bindEvent() {
        this.onMouseDown = (event) => {
            if (event.which === 1) {
                this.pointerDown = true;
            }
            this.clicking = new Date().getTime();
            this.pointer.x = (event.offsetX / this.canvasWidth) * 2 - 1;
            this.pointer.y = -(event.offsetY / this.canvasHeight) * 2 + 1;
            this.handleEvent(event);
            return true;
        };
        this.eventMap.click = {};
        this.labelRenderer.domElement.addEventListener('mousedown', this.onMouseDown, false);
    }

    bindEvent2() {
        this.onMouseDown = (event) => {
            if (event.which === 1) {
                this.pointerDown = true;
            }
            console.log(event);
            this.pointer.x = event.clientX;
            this.pointer.y = event.clientY;
            this.handleEvent(event);
            return true;
        };
        this.eventMap.click = {};
        this.labelRenderer.domElement.addEventListener('pointerdown', this.onMouseDown, false);
    }


    refreshScene() {
        this.needTransform = myObject['变幻调试开关'];
        this.env = myObject['所在环境'];
        this.load = false;
        this.Destroy();
        this.Create();
        this.on('ready', () => {
            // this.reset();
        })
    }

    reset() {
        if(myObject['坐标轴线开关']){
            this.axeshelper.visible = true
        }else{
            this.axeshelper.visible = false
        }
        if(myObject['帧率工具开关']){
            this.stats.dom.style.display = 'block';
        }else{
            this.stats.dom.style.display = 'none';
            this.axeshelper.visible = false
        }
        if(myObject['预览工具开关']){
            this.panel.domElement.style.display = 'flex'
        }else{
            this.panel.domElement.style.display = 'none'
        }
        this.clock.start();
        if(myObject['生长动画开关']){
            this.initGrowAnimation();
        }
        
        if(myObject['炸开动画开关']){
            this.boomAnimation();
        }
    }

    testModel2() {
        const loader = new FBXLoader();
        this.actions = [];
        loader.load(
            'https://cdn.meos.center/yushuweb/animation3.fbx?v=1',
            (obj) => {
                this.root.add(obj);
                this.load = true;
                this.stopLoading();
                this.mixer = new THREE.AnimationMixer(obj);
                const duration = obj.animations[obj.animations.length - 1].duration;
                obj.animations.forEach((i, index) => {
                    // i.resetDuration();
                    // i.trim();
                    // console.log(i);
                    // i.duration = duration;
                    // i.resetDuration();
                    const action = this.mixer.clipAction(i);

                    // action.setDuration(duration).setEffectiveTimeScale(1);
                    if (index > 0) {
                        action.time = obj.animations[index - 1].duration;
                        action.startTime = action.time;
                    }
                    // action.duration = duration;
                    // action.startAt(i.duration);
                    action.clampWhenFinished = true;
                    action.loop = THREE.LoopOnce;
                    // action.zeroSlopeAtEnd = false;
                    // action.play();
                    this.actions.push(action);
                });
                this.actions.map((ac, index) => {
                    if (index > 0) {
                        // ac.setDuration(ac.duration - this.actions[index - 1].duration);
                    }
                    // console.log(ac);
                    // ac.play();
                });

                this.mixer.addEventListener('finished', () => {
                    this.loopAnimation();
                });
                this.actions[0].play();
                this.index = 0;
            }
        );
    }

    createPlaneStencilGroup2(mesh, plane, renderOrder) {
        const group = new THREE.Group();
        const baseMat = new THREE.MeshBasicMaterial();
        baseMat.depthWrite = false;
        baseMat.depthTest = false;
        baseMat.colorWrite = false;
        baseMat.stencilWrite = true;
        baseMat.stencilFunc = THREE.AlwaysStencilFunc;

        // back faces
        const mat0 = baseMat.clone();
        mat0.side = THREE.BackSide;
        mat0.clippingPlanes = [plane];
        mat0.stencilFail = THREE.IncrementWrapStencilOp;
        mat0.stencilZFail = THREE.IncrementWrapStencilOp;
        mat0.stencilZPass = THREE.DecrementWrapStencilOp;

        const mesh0 = mesh.clone();
        mesh0.material = mat0;
        mesh0.renderOrder = renderOrder;
        group.add(mesh0);

        // front faces
        const mat1 = baseMat.clone();
        mat1.side = THREE.FrontSide;
        mat1.clippingPlanes = [plane];
        mat1.stencilFail = THREE.DecrementWrapStencilOp;
        mat1.stencilZFail = THREE.DecrementWrapStencilOp;
        mat1.stencilZPass = THREE.IncrementWrapStencilOp;

        const mesh1 = mesh.clone();
        mesh1.material = mat1;
        mesh1.renderOrder = renderOrder;

        group.add(mesh1);

        return group;
    }

    testModel3() {
        this.camera.position.set(2, 2, 2);
        const planeGeom = new THREE.PlaneGeometry(4, 4);
        const plane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 0);
        const planeMat = new THREE.MeshStandardMaterial({
            color: 0xE91E63,
            clippingPlanes: [],
            stencilWrite: true,
            stencilRef: 0,
            stencilFunc: THREE.NotEqualStencilFunc,
            stencilFail: THREE.ReplaceStencilOp,
            stencilZFail: THREE.ReplaceStencilOp,
            stencilZPass: THREE.ReplaceStencilOp
        });

        const po = new THREE.Mesh(planeGeom, planeMat);
        po.renderOrder = 1.1;

        po.onAfterRender = (renderer) => {
            renderer.clearStencil();
        };
        this.po = po;
        this.plane = plane;
        if (this.po && this.plane) {
            this.plane.coplanarPoint(this.po.position);
            this.po.lookAt(
                this.po.position.x - this.plane.normal.x,
                this.po.position.y - this.plane.normal.y,
                this.po.position.z - this.plane.normal.z
            );
        }
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.shadowMap.enabled = true;
        this.Scene.add(po);
        const geometry = new THREE.BoxGeometry(1, 1, 1);
        const material = new THREE.MeshStandardMaterial({
            color: 0xFFC107,
            clippingPlanes: [plane]
        });
        const boxobject = new THREE.Group();
        this.Scene.add(boxobject);
        const clippedColorFront = new THREE.Mesh(geometry, material);
        clippedColorFront.renderOrder = 6;
        const stencilGroup = this.createPlaneStencilGroup2(clippedColorFront, plane, 1);
        this.Scene.add(stencilGroup);
        this.Scene.add(clippedColorFront);
        this.load = true;
        this.stopLoading();
    }

    playNext() {
        this.actions[1].play();
        this.actions[0].crossFadeTo(this.actions[1], 0.5, true);
        // this.actions[0].crossFadeTo(this.actions[1], 1);
    }

    loopAnimation() {
        // console.log(this.index);
        this.actions[this.index].reset().stop();
        if (this.index >= this.actions.length - 1) {
            this.actions[0].play();
            this.index = 0;
        } else {
            if (this.actions[this.index + 1].startTime) {
                this.actions[this.index + 1].time = this.actions[this.index + 1].startTime;
            }
            this.actions[this.index + 1].play();
            this.index += 1;
        }
    }

    async initBuildingBim() {
        this.root.castShadow = true;
        // this.root.receiveShadow = true;
        // this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
        // this.renderer.toneMappingExposure = 0.85;
        const geometry = new THREE.PlaneGeometry( 1000, 300 );
        this.cubeRenderTarget = new THREE.WebGLCubeRenderTarget(1024, {
            generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter
        });
        const cubeCamera = new THREE.CubeCamera( 1, 100000, this.cubeRenderTarget );
        this.Scene.add(cubeCamera);
        const material = new THREE.ShadowMaterial({
            metalness: 0,
            opacity: 0.25,
            transparent: true,
            roughness: 0,
            side: THREE.FrontSide} );
        const gui = new GUI()
        const cubeFolder = gui.addFolder('Cube')
        // const data = {
        //     color: material.color.getHex(),
        //     emissive: material.emissive.getHex(),
        // }
        
        // const meshStandardMaterialFolder = gui.addFolder('THREE.MeshStandardMaterial')
        
        // meshStandardMaterialFolder.addColor(data, 'color').onChange(() => {
        //     material.color.setHex(Number(data.color.toString().replace('#', '0x')))
        //     material.needsUpdate = true
        // })
        const plane = new THREE.Mesh( geometry, material );
        plane.receiveShadow = false;
        plane.rotateX(-Math.PI / 2);
        plane.translateX(200);
        plane.position.y = 0.14;
        this.Scene.add( plane );
        await this.initLightAndShadow2();
        this.type = 'bimBin';
        const params = getAllUrlParams(),
            r = [];

        const {
            projectid
        } = params;
        let rootPath;
        this.projectId = 'Pj9909990006';
        let floorBimId = 'Fl990999000297efbe8cce5a4b399c03aee1b773aff0'
        const geometries = [];
        this.revitLoader = new RevitLoader('https://adm-revit.ysbdtp.com');
        await this.revitLoader.singleLoad(`${this.projectId}/${floorBimId}`, {
            name: 'CFCSFL',
            color: '#FF00FF'
        }, (cancel) => { this._cancelFloorMesh = cancel; }, true).then(((floorId) => (meshWidthMeshRefList) => {
            if (floorId === floorBimId) {
                meshWidthMeshRefList.forEach((meshWidthMeshRef) => {
                    const { mesh, meshRef } = meshWidthMeshRef;
                    // mat.side = THREE.DoubleSide;
                    geometries.push(mesh.geometry);
                });
            }
        })(floorBimId));
        const geo = mergeBufferGeometries(geometries);
        const material2 = new THREE.MeshStandardMaterial({ color: '#ff00ff' });
        const mesh = new THREE.Mesh(geo, material2);
        setMeshUpToY(mesh);
        mesh.receiveShadow = true;
        applyMapForMesh(mesh, 'CFCSFL');
        this.root.add(mesh);
        this.load = true;
    }

    async initModelBim() {
        this.type = 'bimBin';
        const params = getAllUrlParams();

        const {
            meshurl, floor, projectid, scenename
        } = params;

        let rootPath,
            floorBimId,
            category,
            sourceId;
        if (scenename) {
            const pathNameArr = scenename.split('-');
            this.projectId = pathNameArr[0];
            this.sceneName = pathNameArr[1];
            if (this.sceneName) {
                super.Create({ projectId: this.projectId, sceneName: this.sceneName });
            }
        } else if (meshurl) {
            const devices = meshurl.split('/');
            floorBimId = devices[0];
            rootPath = `${projectid}/${floorBimId}`;
            category = [{
                name: devices[1],
                CName: devices[1]
            }];
            sourceId = devices[devices.length - 1].match(/\d+/)[0];
        } else if (floor) {
            sourceId = undefined;
            floorBimId = floor;
            rootPath = `${projectid}/${floorBimId}`;
            category = [{
                name: 'OST_Floors',
                CName: '楼板'
            },
            {
                name: 'OST_StructuralColumns',
                CName: '结构柱'
            },
            {
                name: 'OST_StairsRailing',
                CName: '楼梯'
            },
            {
                name: 'OST_Walls',
                CName: '墙'
            }, {
                name: 'OST_PipeFitting',
                CName: '管件'
            },
            {
                name: 'OST_PipeAccessory',
                CName: '管道附件'
            },
            {
                name: 'OST_PipeCurves',
                CName: '管道'
            },
            {
                name: 'OST_DuctFitting',
                CName: '风管管件'
            },
            {
                name: 'OST_DuctCurves',
                CName: '风管'
            },
            {
                name: 'OST_DuctAccessory',
                CName: '风管附件'
            },
            {
                name: 'OST_DuctTerminal',
                CName: '风道末端'
            }, {
                name: 'OST_MechanicalEquipment',
                CName: '机械设备'
            },
            {
                name: 'OST_ElectricalEquipment',
                CName: '电气设备'
            },
            {
                name: 'OST_ElectricalFixtures',
                CName: '电气装置'
            },
            {
                name: 'OST_FireAlarmDevices',
                CName: '火警设备'
            },
            {
                name: 'OST_LightingFixtures',
                CName: '照明设备'
            },
            {
                name: 'OST_SecurityDevices',
                CName: '安全设备'
            },
            {
                name: 'OST_SpecialityEquipment',
                CName: '专用设备'
            }];
        }
        if (!scenename) {
            this.projectId = projectid;
            this.peloader = new PELoader(this);
            this.peloader.store = this.store;
            this.peloader.root = this.root;
            this.u3dMaterlsLoader = new U3dMaterlsLoader(this);
            this.u3dMaterlsLoader.type = this.type;
            if (!this.textureMap) {
                try {
                    this.textureMap = await this.u3dMaterlsLoader.getTextureMap();
                } catch (e) {
                    console.log(e);
                }
            }
            await this.peloader.loadMeshes(category, rootPath, {
                floorBimId,
                sourceId,
                type: 'device',
                upY: true,
                textureMap: this.textureMap
            });
        }
        
        this.load = true;
        this.stopLoading();
    }

    handleColorChange( color, value, converSRGBToLinear = false ) {



        if ( typeof value === 'string' ) {

            value = value.replace( '#', '0x' );

        }

        color.setHex( value );

        if ( converSRGBToLinear === true ) color.convertSRGBToLinear();


    }

    renderClouds() {
        this.renderer.setRenderTarget( this.clouds.renderTarget );
        this.renderer.autoClear = false;
		this.renderer.clear( true, true, true );
        this.renderer.render(this.Scene, this.camera);
        this.clouds.cloudsMaterial.uniforms['uPass'] = 1;
        this.clouds.cloudsMaterial.uniforms['tCloudInfos'] = this.clouds.renderTarget.texture;

        this.renderer.setRenderTarget(null);
        this.renderer.render(this.Scene, this.camera);
    }

    Update() {
        if (this.stats) {
            this.stats.update();
        }
        if(this.time){
            this.time.value += this.clock.getDelta();
        }
        
        if(this.realisticSceneLoader){
            this.realisticSceneLoader.animate(this.Scene);
        }
        
        this.renderer.render(this.Scene, this.camera);
        
        if (this.mixer) {
            const delta = this.clock.getDelta();
            this.mixer.update(delta);
        }
        if(this.growTweenGroup && myObject['生长动画开关']){
            this.growTweenGroup.update();
        }
        if(this.boomTweenGroup && myObject['炸开动画开关']){
            this.boomTweenGroup.update();
        }
        this.controls.update();
        if (this.particleManagers && this.particleManagers.length && this.load) {
            for (let i = 0; i < this.particleManagers.length; i++) {
                this.particleManagers[i].Update();
            }
        }
        if (this.lineAnimationArr && this.lineAnimationArr.length && this.load) {
            for (let i = 0; i < this.lineAnimationArr.length; i++) {
                this.lineAnimationArr[i].Update();
            }
        }
        // 相机移动
        if (this.cameraManager.isMoving) {
            this.cameraManager.Update();
        }
    }

    restoreCamera() {
        const params = getAllUrlParams();
        const {
            meshurl, floor, projectid, scenename
        } = params;
        if (scenename) {
            this.controls.reset();
        } else if (meshurl) {
            const devices = meshurl.split('/'),
                floorBimId = devices[0];
            const rootPath = `${projectid}/${floorBimId}`;
            const sourceId = devices[devices.length - 1].match(/\d+/)[0];
            const allPoints = [],
                box3 = new THREE.Box3();
            const SourceId = `${floorBimId}:${sourceId}`;
            if (this.store.state.allMeshSourceIDIC.has(SourceId)) {
                const obj = this.store.state.allMeshSourceIDIC.get(SourceId);
                box3.setFromObject(this.root.getObjectById(obj.meshId));
            }
            return this.cameraManager.setCamera(box3, new THREE.Vector3(1, 1, 1).normalize(), false, 1.2, false);
        } else {
            // const allPoints = [],
            //     box3 = new THREE.Box3();
            // this.store.state.allMeshSourceIDIC.forEach((obj, sourceID) => {
            //     allPoints.push(obj.box.min);
            //     allPoints.push(obj.box.max);
            // });
            // box3.setFromPoints(allPoints);
            // return this.cameraManager.setCamera(box3, new THREE.Vector3(1, 1, 1).normalize(), false, 1, false);
        }
    }

    Destroy() {
        this.Scene.children.map(c => {
            this.destroyChild(c);

            c.clear();
        });
        while (this.Scene.children.length > 0) {
            this.Scene.remove(this.Scene.children[0]);
        }
        // 清除场景全部child
        this.Scene.clear();
        // 卸载场景
        // this.renderer.renderLists.dispose();
        // this.renderer.dispose();
    }
}
